package com.bird.component.sensitive

import cn.hutool.dfa.SensitiveUtil
import com.bird.component.lang.util.fixedPhone
import com.bird.component.lang.util.idCardNum
import com.bird.component.lang.util.isnull
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider

class StringSensitiveJsonSerializer(
    private val serializer: JsonSerializer<Any>?
) : JsonSerializer<Any>() {
    //重写序列化
    override fun serialize(p0: Any?, p1: JsonGenerator?, p2: SerializerProvider?) {
        var result: String? = null
        if (p0 is String && p0.isNotBlank()) {
            result = processSensitiveField(p0)
        }
        if (serializer.isnull()) {
            p2?.defaultSerializeValue(result, p1)
        } else {
            serializer?.serialize(result, p1, p2)
        }
    }

    /**
     * 对于输入进行脱敏处理
     * @param input 需要处理的字段
     * @return 脱敏后的字段
     */
    private fun processSensitiveField(input: String): String {
        if (input.isBlank()) {
            return input
        }
        val result = input.trim()
        val strLen = input.length
        return if (strLen > 18) {
            return result.substring(0, 4) + "***" + result.substring(result.length - 4)
        } else if (strLen == 18) {
            result.idCardNum(6, 3)
        } else if (strLen >= 11) {
            result.fixedPhone()
        } else {
            result.replaceRange(0, result.length - 1, "*")
        }
    }
}